package com.py.framework.core.aspectj;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.py.framework.core.entity.SysLogEntity;
import com.py.framework.core.helper.HttpServletHelper;
import com.py.framework.core.helper.SysLogHelper;
import com.py.framework.core.helper.UrlHelper;
import com.py.framework.core.log.ExceptionLogger;

/**
 * 日记记录AOP实现
 * @author Leegern
 * @date   2018年5月10日
 */
@Aspect
public class AccessLogAspect {
	
	@Autowired
	private UrlHelper urlHelper;
	
	/**
	 * 切入方法
	 * @param joinPoint
	 * @return
	 * @throws Throwable
	 */
	@Around("execution(* com.py.**.controller..*.*(..)) and !execution(* com.py.framework.core.controller..*Base*.*(..))")
	public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
		Object result = null;
		try {
			ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = servletRequestAttributes.getRequest();
			// 获取请求地址
			String requestPath = request.getRequestURI();
			String servletPath = request.getServletPath();
			
			SysLogEntity entity = new SysLogEntity();
			String jdToken = HttpServletHelper.getUserToken(request);
			entity.setRequestContent(HttpServletHelper.getRequestParams(request));
			entity.setRequestIp(HttpServletHelper.getGuestIP(request));
			entity.setRequestUrl(requestPath);
			if (StringUtils.isBlank(servletPath)) {
	            String ctxPath = request.getContextPath();
	        	servletPath    = requestPath.replaceFirst(ctxPath, "");
	        }
			entity.setShortRequestUrl(servletPath);
			
			// 异步发送日志
			SysLogHelper.postAsyncSysLog(jdToken, urlHelper.getBaseServerUrl(), JSON.toJSONString(entity));
		} catch (Exception e) {
			ExceptionLogger.error(e);
		}
		// 执行完方法的返回值：调用processd方法，就会触发切入点方法执行
		result = joinPoint.proceed();
		return result;
	}
}